package hn.cch.web.socket.websocket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.CloseReason;
import javax.websocket.EndpointConfig;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;

@Component
@ServerEndpoint(value = "/my", configurator = MyConfigurator.class)
public class MyServerEndpoint {

    private static final Logger logger = LoggerFactory.getLogger(MyServerEndpoint.class);

    private Session session;

    @OnOpen
    public void onOpen(Session session, EndpointConfig endpointConfig) {
        this.session = session;
        try {
            session.getBasicRemote().sendText("open");
        } catch (IOException e) {
            logger.error(e.getMessage());
        }
    }

    @OnMessage
    public  void onMessage(String message) {
        logger.debug(message);
        try {
            session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            logger.error(e.getMessage());
        }

    }

    @OnClose
    public void onClose(Session session, CloseReason closeReason){
        logger.debug("close:{}", closeReason.getReasonPhrase());
    }


    @OnError
    public void onError(Session session, Throwable throwable){
        logger.error("error:{}", throwable.getMessage());
        // throwable.printStackTrace();
    }


}
